package com.jsyh.maidu.activity.me;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.jsyh.maidu.R;
import com.jsyh.maidu.activity.MainActivity;
import com.jsyh.maidu.alipay.PayResult;
import com.jsyh.maidu.model.AliPatModel;
import com.jsyh.maidu.model.SubmitOrder;
import com.jsyh.maidu.model.WXpayModel;
import com.jsyh.maidu.presenter.PayActivePresenter;
import com.jsyh.maidu.utils.Utils;
import com.jsyh.maidu.views.PayActiveView;
import com.jsyh.shopping.uilibrary.adapter.listview.BaseAdapterHelper;
import com.jsyh.shopping.uilibrary.adapter.listview.QuickAdapter;
import com.jsyh.shopping.uilibrary.views.MyListView;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class OrderSureActivity extends Activity implements View.OnClickListener,PayActiveView{

    SubmitOrder orderMsg;
    TextView tv_difftex,tv_title;
    MyListView lv_order;
    Button btn_home,btn_orderlist;
    ImageView iv_back;
    private static final int SDK_PAY_FLAG = 1;

    private static final int SDK_CHECK_FLAG = 2;
    QuickAdapter<SubmitOrder.sunorder> quickadpater;
    String aliinfo="";
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        finish();
                        Utils.showToast(OrderSureActivity.this, "支付成功");
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Utils.showToast(OrderSureActivity.this,"支付结果确认中");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Utils.showToast(OrderSureActivity.this, "支付失败");
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    if (!(boolean) msg.obj)
                        Utils.showToast(OrderSureActivity.this, "检查结果为：" + msg.obj);
                    else {

                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_sure);
        orderMsg= (SubmitOrder) getIntent().getSerializableExtra("ordermsg");
        InitView();
    }
    public void InitView()
    {
        tv_difftex= (TextView) findViewById(R.id.tv_OS_difftext);
        lv_order= (MyListView) findViewById(R.id.lv_OS_diffdetail);

        tv_title= (TextView) findViewById(R.id.title);
        iv_back= (ImageView) findViewById(R.id.back);
        btn_home= (Button) findViewById(R.id.btn_ordersure_home);
        btn_orderlist= (Button) findViewById(R.id.btn_ordersure_orderlist);

        iv_back.setOnClickListener(this);
        btn_orderlist.setOnClickListener(this);
        btn_home.setOnClickListener(this);

        tv_title.setText("订单支付");

        if (orderMsg.getSuborder_list().size()==1)
        {
            tv_difftex.setVisibility(View.GONE);
        }else {
            tv_difftex.setVisibility(View.VISIBLE);
            tv_difftex.setText("由于您的商品由不用的商家发出，此订单将分为"+orderMsg.getSuborder_list().size()+""+"个不同的子订单配送");
        }
        quickadpater=new QuickAdapter<SubmitOrder.sunorder>(this,R.layout.ordersure_order_item) {
            @Override
            protected void convert(BaseAdapterHelper helper, SubmitOrder.sunorder item) {
                helper.setText(R.id.tv_osoi_ordernum,item.getOrder_sn());
                helper.setText(R.id.tv_osoi_orderprice,item.getOrder_amount_formated());
                helper.setText(R.id.tv_osoi_ordertrans,item.getShipping_name());
            }
        };
        lv_order.setAdapter(quickadpater);
        quickadpater.addAll(orderMsg.getSuborder_list());



    }


    @Override
    public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.btn_ordersure_home:
                Intent hintent=new Intent(this, MainActivity.class);
                startActivity(hintent);
                break;

            case R.id.btn_ordersure_orderlist:
                Intent ointtent=new Intent(this,MyOrderActivity.class);
                startActivity(ointtent);
                break;

            case R.id.back:
                finish();
                break;
        }
    }

    @Override
    public void getWXinfo(WXpayModel wxpay) {
        {
            if (wxpay.getCode().equals("1")) {
                final IWXAPI api = WXAPIFactory.createWXAPI(this, null);
                // 将该app注册到微信
                api.registerApp("wxb6b89ad7d9ebfbb0");

                PayReq req = new PayReq();

                req.appId = wxpay.getData().getPayinfo().getAppId();

                req.partnerId = wxpay.getData().getPayinfo().getPartnerId();
                req.prepayId = wxpay.getData().getPayinfo().getPrepayId();
                req.packageValue = "Sign=WXPay";
                req.nonceStr = wxpay.getData().getPayinfo().getNonceStr();
                req.timeStamp = wxpay.getData().getPayinfo().getTimeStamp();
                req.sign = wxpay.getData().getPayinfo().getSign();
                api.sendReq(req);


                finish();
            }else {
                Toast.makeText(this,wxpay.getMsg(),Toast.LENGTH_LONG).show();
            }

        }
    }

    @Override
    public void getALiinfo(final AliPatModel ali) {
        // 必须异步调用
        aliinfo=ali.getData().getPayinfo();
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }
    Runnable payRunnable = new Runnable() {

        @Override
        public void run() {
            PayTask alipay = new PayTask(OrderSureActivity.this);
            String result = alipay.pay(aliinfo);

            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    };


}
